package server;

import java.io.InputStream;
import java.net.Socket;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            HttpServlet httpServlet = getHttpServlet(request);
            if (httpServlet == null) {
                // 静态资源处理
                response.outputHtml(mapper ,request);
            } else {
                // 动态资源servlet请求
                httpServlet.service(request, response);
            }

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private HttpServlet getHttpServlet(Request request) {
        try {
            String host = request.getHost();
            String url = request.getUrl();
            String[] split = url.split("/");
            //项目名为context
            String context = split[1];
            String servletName = url.substring(context.length() + 1);
            //localhost 与 127.0.0.1 可以做互相转换， 此处未做处理
            Mapper.MappedHost mappedHost = mapper.getHostMap().get(host);
            Mapper.MappedContext mappedContext = mappedHost.getContextMap().get(context);
            HttpServlet httpServlet = mappedContext.getServletMap().get(servletName);
            return httpServlet;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
